<?php

namespace App\Util;

class RequestUtil
{
    /**
     * @var string 路由地址
     */
    protected $route;
    /**
     * @var string 控制器名（含命名空间）
     */
    protected $controllerWithNamespace;
    /**
     * @var string 控制器名
     */
    protected $controller;
    /**
     * @var string 方法
     */
    protected $action;
    /**
     * @var string url（不含域名和 qs）
     */
    protected $path;

    /**
     * @var static 单例模式
     */
    protected static $instance;

    public function __construct()
    {
        $this->parseCurrentRouteInfo();
    }

    /**
     * 单例模式
     */
    public static function getInstance()
    {
        if (static::$instance instanceof static) {
            return static::$instance;
        }
        static::$instance = new static();
        return static::$instance;
    }

    /**
     * 获取当前路由信息
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/14
     */
    public function parseCurrentRouteInfo()
    {
        $routeInfo = request()->route();
        $route = $routeInfo[1]['uses'];

        [$controllerWithNamespace, $action] = explode('@', $route);

        $controller = class_basename($controllerWithNamespace);

        $this->setRoute($route);
        $this->setControllerWithNamespace($controllerWithNamespace);
        $this->setController($controller);
        $this->setAction($action);
        $this->setPath(request()->path());
    }

    public function getRoute(): string
    {
        return $this->route;
    }

    public function setRoute(string $route): void
    {
        $this->route = $route;
    }

    public function getControllerWithNamespace(): string
    {
        return $this->controllerWithNamespace;
    }

    public function setControllerWithNamespace(string $controllerWithNamespace): void
    {
        $this->controllerWithNamespace = $controllerWithNamespace;
    }

    public function getController(): string
    {
        return $this->controller;
    }

    public function setController(string $controller): void
    {
        $this->controller = $controller;
    }

    public function getAction(): string
    {
        return $this->action;
    }

    public function setAction(string $action): void
    {
        $this->action = $action;
    }

    public function getPath(): string
    {
        return $this->path;
    }

    public function setPath(string $path): void
    {
        $this->path = $path;
    }
}
